<template>
  <div class="mu_box multiple_list_box">
    <div class="btn_add" @click="handleAddMany">
      <span class="el-icon-circle-plus-outline"></span>
      创建
    </div>
    <div class="bg_title">活跃的反馈模拟</div>
    <div class="multiple_list">
      <div class="item" v-for="(item, index) in list" :key="index">
        <div class="title">
          {{ item.properties.simulationName }}
        </div>
        <div class="icons">
          <div
            @click="handlePlay(item)"
            :class="
              item.isRunType == 'pause'
                ? 'el-icon-video-pause'
                : 'el-icon-video-play'
            "
            style="color: #707071; font-size: 13px"
            :style="{
              color: item.isRunType == 'pause' ? '#2680D2' : '#707071',
            }"
          ></div>
          <div
            v-if="item.isRunType !== 'run'"
            @click="handlePlay(item, 'stop')"
            class="cl_play"
          ></div>
          <div class=""></div>
          <div class="line"></div>
          <div
            slot="reference"
            @click="handleEdit(item)"
            class="el-icon-edit-outline"
            style="color: #707071; font-size: 13px"
          ></div>

          <div class="line"></div>
          <div
            @click="handleDelSiddhi(item)"
            class="el-icon-delete"
            style="color: #707071; font-size: 13px"
          ></div>
        </div>
      </div>
    </div>
    <div class="bg_title" v-if="inActiveSimulations.length !== 0">
      不活跃的反馈模拟
    </div>
    <div class="multiple_list">
      <el-tooltip
        class="item"
        effect="dark"
        :content="item.exceptionReason"
        placement="top-start"
        v-for="(item, index) in inActiveSimulations"
        :key="index"
      >
        <div slot="content" style="width: 300px">
          {{ item.exceptionReason }}
        </div>
        <div class="item">
          <div class="title">
            {{ item.properties.simulationName }}
          </div>
          <div class="icons">
            <div
              class="el-icon-video-play"
              style="color: #707071; font-size: 13px"
            ></div>
            <div class="line"></div>
            <!-- @click="handleEdit(item)" -->
            <div
              @click="handleEdit(item)"
              slot="reference"
              class="el-icon-edit-outline"
              style="color: #707071; font-size: 13px"
            ></div>

            <div class="line"></div>
            <div
              @click="handleDelSiddhi(item)"
              class="el-icon-delete"
              style="color: #707071; font-size: 13px"
            ></div>
          </div>
        </div>
      </el-tooltip>
    </div>
    <el-drawer
      :modal="true"
      :wrapperClosable="false"
      size="46%"
      title="多例模拟"
      :visible.sync="drawer"
      direction="rtl"
      :before-close="handleClose"
    >
      <MultipleDw
        :isEditAdd="isEditAdd"
        @handleSub="handleSub"
        ref="MultipleDw"
        @handleCloes="drawer = false"
      ></MultipleDw>
    </el-drawer>
  </div>
</template>

<script>
import {
  getFeed,
  listAttributes,
  delFeed,
  playFeed,
  edgeRunApp,
  feedStatus,
  listSiddhiApps,
} from "@/api/siddhi";
import _ from "lodash";
import MultipleDw from "./MultipleDw.vue";
import { mergeSources } from "../js/index";
import { mapGetters } from "vuex";
export default {
  components: {
    MultipleDw,
  },
  data() {
    return {
      isEditAdd: false,
      inActiveSimulations: [],
      drawer: false,
      list: [],
      // msg: "2022-08-23T02:03:53.280Z",
      show: false,
      form: {
        name: "",
        region: "",
        date1: "",
        date2: "",
        delivery: false,
        type: [],
        resource: "",
        desc: "",
        timer: null,
      },
    };
  },
  created() {
    this.getFeed();
    this.createSetInterval();
  },
  computed: {
    // ...mapGetters(["listSiddhiApps"]),
  },
  // 离开页面销毁轮询器
  destroyed() {
    this.stopSetInterval();
  },
  methods: {
    // 启动
    async handlePlay(item, type) {
      // pause
      // 先判断当前下的流是否是stop状态的
      const { sources, properties } = item;
      if (type == "stop") {
        const res = await playFeed({
          simulationName: properties.simulationName,
          action: "stop",
        });
        item.isRunType = "run";
        this.feedStatus(properties, item.isRunType);
        return;
      }
      const siddhiAppNames = sources.map((item) => item.siddhiAppName);
      const res = await listSiddhiApps();
      const resSiddhiList = res.data;
      const childrenNames = resSiddhiList.filter((item) =>
        siddhiAppNames.includes(item.siddhiAppName)
      );
      const stopSiddhiNames = childrenNames.filter(
        (item) => item.mode == "STOP"
      );
      console.log(stopSiddhiNames, "treeEdgeData", item);
      const names = stopSiddhiNames.map((item) => item.siddhiAppName);
      let htm = ``;

      if (stopSiddhiNames.length !== 0) {
        names.forEach((item) => {
          htm += `<div>${item}</div>`;
        });
        this.$confirm(htm, "以下Siddhi应用程序需要开始模拟.…", {
          dangerouslyUseHTMLString: true,
          confirmButtonText: "开始模拟",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async (confirm) => {
            const res = await playFeed({
              simulationName: properties.simulationName,
              action: item.isRunType,
            });
            if (item.isRunType == "resume" || item.isRunType == "run") {
              this.$msg({
                type: "success",
                message: properties.simulationName + "模拟启动成功",
              });
            }
            // this.$store.dispatch("siddhi/setLogData", {
            //   message: properties.simulationName + "启动成功!",
            //   type: "INFO",
            // });
            Promise.all(
              names.map(async (item) => {
                const form = { siddhiAppName: item, variables: {} };
                return await edgeRunApp(JSON.stringify(form));
              })
            ).then((res) => {
              this.feedStatus(properties);
              if (item.isRunType == "pause") {
                item.isRunType = "resume";
              } else {
                item.isRunType = "pause";
              }
              // if (item.isRunType == "run") {
              //   item.isRunType = "pause";
              // }
              // resume

              console.log(res, "执行完毕");
            });
          })
          .catch((err) => {});
      } else {
        const res = await playFeed({
          simulationName: properties.simulationName,
          action: item.isRunType,
        });
        if (item.isRunType == "resume" || item.isRunType == "run") {
          this.$msg({
            type: "success",
            message: properties.simulationName + "模拟启动成功",
          });
        }

        console.log(res, "resresresres");
        if (item.isRunType == "pause") {
          item.isRunType = "resume";
        } else {
          item.isRunType = "pause";
        }
        this.feedStatus(properties, item.isRunType);
      }

      // treeEdgeData
    },
    // 开始定时任务--
    feedStatus(row) {
      console.log(row, "======");
      if (row.time) {
        clearInterval(row.time);
        row.time = null;
      } else {
        row.time = setInterval(() => {
          feedStatus(row.simulationName);
        }, 3000);
      }
    },
    // 开启轮询  如果存在则先销毁定时器后重新开启
    createSetInterval() {
      this.stopSetInterval();
      let _this = this;
      this.timer = setInterval(() => {
        _this.getFeed();
      }, 3000);
    },
    // 关闭轮询
    stopSetInterval() {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    },
    handleDelSiddhi(item) {
      this.$confirm("是否确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        delFeed(item.properties.simulationName).then((res) => {
          this.$msg({
            type: "success",
            message: "删除成功,请等待列表更新",
            time: null,
          });
          // this.getFeed();
        });
      });
    },
    handleSub() {
      this.$msg({
        message: this.isEditAdd
          ? "添加成功,请等待列表更新"
          : "修改成功,请等待列表更新",
        type: "success",
      });
      this.drawer = false;
      // this.getFeed();
    },
    async potinfo(siddhiAppName, streamName) {
      return new Promise(async (resolve) => {
        const res = await listAttributes({
          siddhiAppName,
          streamName,
        });
        // console.log(res, "获取流下的属性");
        const { data } = res;
        const newData = data.map((item) => {
          return {
            ...item,
            isCheck: false,
            value: "",
            type: [item.type],
          };
        });
        resolve(newData);
      });
    },
    // 编辑
    handleEdit(item2) {
      this.isEditAdd = true;
      this.drawer = true;
      this.$nextTick(async () => {
        const newItem = _.cloneDeep(item2);
        this.$refs["MultipleDw"].form = newItem.properties;
        console.log("任务开始", item2);
        if (newItem.sources) {
          Promise.all(
            newItem.sources.map(async (item) => {
              let cloneItem = _.cloneDeep(item);
              let { simulationType, columnNamesList, indices } = cloneItem;

              if (cloneItem.streamName) {
                let res = await this.potinfo(
                  cloneItem.siddhiAppName,
                  cloneItem.streamName
                );
                console.log(res, "任务开始中========");
                cloneItem.isTimestampInterval = cloneItem.timestampInterval
                  ? true
                  : false;
                if (simulationType == "RANDOM_DATA_SIMULATION") {
                  res = res.map((e, i) => {
                    return {
                      ...e,
                      ...cloneItem.attributeConfiguration[i],
                      attributesType: cloneItem.attributeConfiguration[i].type,
                      type: e.type,
                      list:
                        cloneItem.attributeConfiguration[i].list &&
                        cloneItem.attributeConfiguration[i].list[0],
                    };
                  });
                }
                if (simulationType == "DATABASE_SIMULATION") {
                  cloneItem.listStreams = [];
                  columnNamesList = columnNamesList
                    ? columnNamesList.split(",")
                    : [];
                  res = res.map((e, i) => {
                    return {
                      ...e,
                      attributesType: columnNamesList[i]
                        ? columnNamesList[i]
                        : "",
                      type: e.type,
                    };
                  });
                }
                if (simulationType == "CSV_SIMULATION") {
                  cloneItem.listStreams = [];
                  indices = indices ? indices.split(",") : [];
                  res = res.map((e, i) => {
                    return {
                      ...e,
                      value: indices[i] ? indices[i] : "",
                      attributesType: indices[i] ? indices[i] : "",
                      type: e.type,
                    };
                  });
                }
                cloneItem.listAttributes = res;
                cloneItem.name = cloneItem.streamName;

                return cloneItem;
              } else {
                // return {
                //   ...cloneItem,
                // };
              }
            })
          ).then((res) => {
            // 此处打印的是map之后的数据
            res = res.filter((item) => item);
            console.log("任务完成", res);
            this.$refs["MultipleDw"].AnalogSourceObj = mergeSources(res);
          });
        }

        // console.log(mergeSources(newItem.sources), "是否赋值成功");

        // this.$refs["MultipleDw"].AnalogSourceObj = mergeSources(
        //   newItem.sources
        // );
        // console.log(newItem.sources);
      });
    },
    // 添加多例模拟
    handleAddMany() {
      this.isEditAdd = false;
      this.drawer = true;
    },
    handleClose(done) {
      done();
    },
    async getFeed() {
      const res = await getFeed();
      const { message, status } = res.data;
      if (status == "OK") {
        const { activeSimulations, inActiveSimulations } = JSON.parse(message);
        this.list = activeSimulations.map((item) => {
          return {
            ...item,
            show2: false,
            isRunType: "run",
          };
        });
        console.log(activeSimulations, "activeSimulations");
        this.inActiveSimulations = inActiveSimulations;
      }
    },
  },
};
</script>

<style scoped lang='scss'>
@import "~@/styles/mixin.scss";

.mu_box {
  position: relative;
  .btn_add {
    width: 100%;
    height: 32px;
    background-color: #2680d2;
    line-height: 32px;
    text-align: center;
    font-size: 14px;
    color: #fff;
    margin-top: 8px;
    cursor: pointer;
  }
}

.bg_title {
  font-size: 14px;
  color: #666666;
  padding-left: 10px;
  margin: 16px 0;
  font-weight: 600;
}
.multiple_list {
  .cl_play {
    width: 12px;
    height: 12px;
    margin-left: 10px;
    cursor: pointer;
    background-color: rgb(38, 128, 210);
    border-radius: 4px;
  }
  .item {
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    height: 32px;
    padding: 0 10px;
    &:hover {
      background-color: #ebf5ff;
    }
    .title {
      font-size: 13px;
      color: #666666;
      max-width: 130px;
      @include textoverflow(1);
    }
    .icons {
      display: flex;
      align-items: center;
      .line {
        width: 1px;
        height: 14px;
        background-color: #e4e4e4;
        margin: 0 9px;
      }
      .icon {
        width: 14px;
        height: 14px;
      }
    }
  }
}
.multiple_list_box {
  height: calc(100vh - 145px - 100px) !important;
  overflow: auto;
}
</style>